import asyncio

# 创建最大允许2个协程同时运行的信号量
sem = asyncio.Semaphore(2)


async def limited_task(n):
    async with sem:
        print(f"task start{n}")
        await asyncio.sleep(1)
        print(f"task end {n}")


async def main():
    tasks = [limited_task(_) for _ in range(5)]
    await asyncio.gather(*tasks)


asyncio.run(main())
